package com.akka.demo;

import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;

public class TomcatEmbeddedServletContainerCustomizer implements EmbeddedServletContainerCustomizer {

    private static final Logger LOG = LoggerFactory.getLogger(TomcatEmbeddedServletContainerCustomizer.class);

    @Value("${servlet.container.maxThreads}")
    private int MAX_THREADS;

    @Override
    public void customize(ConfigurableEmbeddedServletContainer factory) {
        if (factory instanceof TomcatEmbeddedServletContainerFactory) {
            customizeTomcat((TomcatEmbeddedServletContainerFactory) factory);
        }
    }

    public void customizeTomcat(TomcatEmbeddedServletContainerFactory factory) {
        factory.addConnectorCustomizers();
        factory.addConnectorCustomizers((Connector connector) -> {
//            org.apache.coyote.http11.Http11Protocol：BIO
//            org.apache.coyote.http11.Http11NioProtocol：NIO
//            org.apache.coyote.http11.Http11Nio2Protocol：NIO2
//            org.apache.coyote.http11.Http11AprProtocol：APR
// 在Tomcat7中，自动选取使用BIO或APR（如果找到APR需要的本地库，则使用APR，否则使用BIO）
// 在Tomcat8中，自动选取使用NIO或APR（如果找到APR需要的本地库，则使用APR，否则使用NIO）
//            Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
//            int defaultMaxThreads = protocol.getMaxThreads();
//            protocol.setMaxThreads(MAX_THREADS);
            Object defaultMaxThreads = connector.getAttribute("maxThreads");
            connector.setAttribute("maxThreads", MAX_THREADS);
            LOG.info("Changed Tomcat connector maxThreads from " + defaultMaxThreads + " to " + MAX_THREADS);
//            Object defaultMaxConnections = connector.getAttribute("maxConnections");
//            LOG.info("Tomcat connector maxConnections is " + defaultMaxConnections + ", or is " + protocol.getMaxConnections());
        });
    }

}